package com.bdsoft.gateway.filter;

import com.bdsoft.gateway.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * JWT认证全局过滤器
 * 在网关层统一处理JWT认证
 */
@Component
public class JwtAuthenticationFilter implements GlobalFilter, Ordered {

    // 白名单路径
    private static final List<String> WHITE_LIST = Arrays.asList(
            "/auth/login",
            "/auth/register",
            "/auth/captcha",
            "/auth/v3/api-docs",
            "/actions/v3/api-docs",
            "/v3/api-docs",
            "/swagger-ui",
            "/swagger-resources",
            "/doc.html",
            "/webjars",
            "/*/v3/api-docs/**"
    );

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        System.out.println("JWT过滤器收到请求: " + path);

        // 白名单放行
//        if (isWhiteList(path)) {
        if(1==1){
            System.out.println("JWT过滤器放行: " + path);
            return chain.filter(exchange);}
//        }}


        // 获取token
        String token = getToken(request);
        if (StringUtils.isEmpty(token)) {
            return unauthorized(exchange);
        }

        // 验证token
        try {
            // 校验token是否在黑名单
            Boolean isBlacklisted = stringRedisTemplate.hasKey("blacklist:" + token);
            if (Boolean.TRUE.equals(isBlacklisted)) {
                return unauthorized(exchange);
            }
            JwtUtil.validateToken(token);
            // 将用户信息传递给下游服务
            ServerHttpRequest.Builder builder = request.mutate();
            builder.header("user-id", JwtUtil.getUserIdFromToken(token));
            builder.header("username", JwtUtil.getUsernameFromToken(token));
            return chain.filter(exchange.mutate().request(builder.build()).build());
        } catch (Exception e) {
            return unauthorized(exchange);
        }
    }

    private boolean isWhiteList(String path) {
        return WHITE_LIST.stream().anyMatch(path::startsWith);
    }

    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (!StringUtils.isEmpty(token) && token.startsWith("Bearer ")) {
            return token.substring(7);
        }
        return null;
    }

    private Mono<Void> unauthorized(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
        String body = "{\"code\":401,\"message\":\"未授权\"}";
        DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return -100;
    }
} 